//
//  WebViewController.swift
//  ToBeBigFE
//
//  Created by mingo on 2020/2/8.
//  Copyright © 2020 com.example. All rights reserved.
//

import UIKit
import WebKit
import Photos
import MobileCoreServices

class WebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

    var webView: WKWebView!
    var url: String? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let config = WKWebViewConfiguration()
        let birdge = BridgeHandler()
        config.userContentController.add(birdge, name: "iOSBridge")
        
        // 注册assets-library协议的handler
        config.setURLSchemeHandler(self, forURLScheme: "assets-library")
        
        webView = WKWebView(frame: UIScreen.main.bounds, configuration: config)
        webView.uiDelegate = self
        
        birdge.webView = webView
        birdge.viewController = self
        birdge.initModules()
        
        let dataStore = WKWebsiteDataStore.default()
        let dateFrom: Date = Date(timeIntervalSince1970: 0)
        dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: dateFrom) {
            
        }
        
        let url = URL(string: self.getLoadUrl())!
        print("load \(url)")
        let request = URLRequest(url: url)
        self.webView.load(request)
        self.view.addSubview(webView)
    }
    
    func getLoadUrl() -> String {
        return url ?? "about:blank"
    }
}

extension WebViewController : WKURLSchemeHandler {
    
    func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
        let req = urlSchemeTask.request
        guard let url = req.url, let scheme = url.scheme else {
            urlSchemeTask.didWKWebViewError(code: NSURLErrorUnsupportedURL)
            return
        }
        
        // 如果scheme是相册的
        if scheme == "assets-library" {
            
            // 通过Photos框架，读取PHAsset
            let result = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
            guard let asset = result.firstObject else {
                // 如果不成功，返回失败
                urlSchemeTask.didWKWebViewError(code: NSURLErrorResourceUnavailable)
                return
            }
            
            // 出来图片
            if asset.mediaType == .image {
                let options = PHImageRequestOptions()
                options.isNetworkAccessAllowed = true
                options.deliveryMode = .highQualityFormat
                options.isSynchronous = false
                options.version = .current
                
                // 请求资源数据
                PHImageManager.default().requestImageData(for: asset, options: options) { data, _, _, _ in
                    guard let data = data else {
                        urlSchemeTask.didWKWebViewError(code: NSURLErrorResourceUnavailable)
                        return
                    }
                    let mimeType = asset.mimeType()
                    
                    // WebView不支持heic，转成jpeg
                    if mimeType == "image/heic" {
                        guard let image = UIImage(data: data), let jpegData = image.jpegData(compressionQuality: 1.0) else {
                            urlSchemeTask.didWKWebViewError(code: NSURLErrorCannotDecodeRawData)
                            return
                        }
                        let resp = URLResponse(
                            url: url,
                            mimeType: "image/jpeg",
                            expectedContentLength: jpegData.count,
                            textEncodingName: nil)
                        urlSchemeTask.didReceive(resp)
                        urlSchemeTask.didReceive(jpegData)
                        urlSchemeTask.didFinish()
                    }
                    
                    // 其他图片
                    else {
                        let resp = URLResponse(
                            url: url,
                            mimeType: mimeType,
                            expectedContentLength: data.count,
                            textEncodingName: nil)
                        urlSchemeTask.didReceive(resp)
                        urlSchemeTask.didReceive(data)
                        urlSchemeTask.didFinish()
                    }
                }
            }
            // 视频处理
            else if asset.mediaType == .video {
                let options = PHVideoRequestOptions()
                options.isNetworkAccessAllowed = true
                options.deliveryMode = .highQualityFormat
                options.version = .current
                
                // 请求video的数据
                PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { avAsset, _, _ in
                    
                    // 转成AVURLAsset，读取data
                    guard let urlAsset = avAsset as? AVURLAsset, let data = try? Data(contentsOf: urlAsset.url) else {
                        urlSchemeTask.didWKWebViewError(code: NSURLErrorCannotDecodeRawData)
                        return
                    }
                    // 返回
                    let mimeType = asset.mimeType()
                    let resp = URLResponse(
                        url: url,
                        mimeType: mimeType,
                        expectedContentLength: data.count,
                        textEncodingName: nil)
                    urlSchemeTask.didReceive(resp)
                    urlSchemeTask.didReceive(data)
                    urlSchemeTask.didFinish()
                }
            } else {
                urlSchemeTask.didWKWebViewError(code: NSURLErrorResourceUnavailable)
            }
        } else if scheme == "file" {
            
        }
    }
    
    func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
        
    }
}

fileprivate extension WKURLSchemeTask {
    func didWKWebViewError(code: Int) {
        let error = NSError(domain: "WKWebViewError", code: code, userInfo: nil)
        self.didFailWithError(error)
    }
}
